package com.itserver.controller.sysController;


import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itserver.pojo.PageResult;
import com.itserver.pojo.Result;
import com.itserver.pojo.sys.Dict;
import com.itserver.pojo.sys.QueryDict;
import com.itserver.service.sys.DictService;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("sys/dict")
public class DictController {
    @Autowired
    private DictService dictService;


    //字典列表
    @GetMapping
    public Result list(QueryDict queryDict) {
        PageResult<Dict> dicts = dictService.list(queryDict);
        return Result.success(dicts);
    }
    // 新增字典
    @PostMapping
    public Result add(@RequestBody Dict dict) {
        dictService.add(dict);
        return Result.success();
    }
    // 编辑
    @PutMapping
    public Result update(@RequestBody Dict dict) {
        dictService.update(dict);
        return Result.success();
    }
    // 删除
    @DeleteMapping
    public Result delete(@RequestParam List<Integer> ids) {
        dictService.delete(ids);
        return Result.success();
    }

    @Data
    public static class OptionDTO {
        private String label;
        private String value;
    }
    @GetMapping("/{type}")
    public Result getByInfo(@PathVariable String type){
        Dict dict = dictService.getByInfo(type);
        if (dict == null) {
            return Result.error("字典不存在");
        }
        String options = dict.getOptions();
        // 把options 转成 list 返回给前端
        try {
            ObjectMapper mapper = new ObjectMapper();
            List<OptionDTO> list = mapper.readValue(options, new TypeReference<>() {});
            return Result.success(list); // 返回 List，Spring 会自动转成 JSON 数组
        } catch (Exception e) {
            return Result.error("字典数据格式错误");
        }
    }
}
